package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author kabuda
 * @create 2022-08-23 16:43
 */
@RequestMapping("/member")
@RestController
public class MemberController {
    @Autowired
    JedisPool jedisPool;

    @Reference
    MemberService memberService;


    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        //从redis获取保存的验证码
        String validateCodeRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        String validateCode = (String) map.get("validateCode");
        //比对用户输入的验证码
        if (validateCode != null && validateCodeRedis != null && validateCodeRedis.equals(validateCode)) {
            Member member = memberService.findByTelephone(telephone);

            //如果没有会员信息，则注册
            if (member == null) {
                Member member1 = new Member();
                member1.setRegTime(new Date());
                memberService.add(member1);
            }

            //向客户端写入cookie，内容为手机号
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            cookie.setPath("/");
            //有效期30天
            cookie.setMaxAge(60 * 60 * 24 * 30);
            response.addCookie(cookie);

            //将member信息存入redis，有效期30分钟
            jedisPool.getResource().setex(telephone, 60 * 30, JSON.toJSON(member).toString());

        } else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }

}
